package com.loong.data.handler;

import com.alibaba.fastjson.JSON;
import com.loong.common.param.BaseIdParam;
import com.loong.common.rabbitmq.dto.MemberDTO;
import com.loong.common.utils.TransformUtils;
import com.loong.data.common.forehead.result.MemberForeheadResult;
import com.loong.data.model.UserModel;
import com.loong.data.repository.UserRepository;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Optional;

/**
 * @Description:
 * @Author: 刘群
 * @Date: 2020/11/12 16:21
 */
@Component
public class UserHandler {

    @Resource
    private UserRepository userRepository;

    @Resource
    private RestHighLevelClient client;

    /**
     * 新增会员信息到es：MQ消费者中调用该方法
     * @param memberDTO 会员参数
     */
    public void saveUserModel(MemberDTO memberDTO) {
        userRepository.save(TransformUtils.transform(memberDTO, UserModel.class));
    }

    /**
     * 更新会员信息到es：MQ消费者中调用该方法
     * @param memberDTO 会员参数
     */
    public void updateUserModel(MemberDTO memberDTO) {
        //创建更新请求
        UpdateRequest request = new UpdateRequest("user",memberDTO.getId().toString());
        //将要更新的数据以json格式封装到请求中
        request.doc(JSON.toJSONString(memberDTO), XContentType.JSON);
        //执行更新请求的操作
        try {
            client.update(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id删除es中的会员信息：MQ消费者中调用该方法
     * @param id 会员id
     */
    public void deleteUserModelById(Long id) {
        userRepository.deleteById(id);
    }

    /**
     * 前台根据会员id查询会员信息
     * @param userId 会员id
     * @return 会员
     */
    public MemberForeheadResult findUserModelById(Long userId) {
        Optional<UserModel> optional = userRepository.findById(userId);
        if (optional.isPresent()) {
            return TransformUtils.transform(optional.get(), MemberForeheadResult.class);
        }
        return null;
    }
}
